/*
 * util.c
 *
 *  Created on: 2024年12月20日
 *      Author: lsc
 */

#include <stdlib.h>
#include <stdint.h>
#include "sm2.h"
#include "istd_lib.h"
extern const SM2_Jacobian_Point SM2_G;
extern const sm2_uint256_t SM2_A;
extern const sm2_uint256_t SM2_B;


uint32_t sm2_concat_params(uint8_t **concat_m, const uint8_t pub[64], const char *id, unsigned short n_bytes)
{
    // Z_A=H256(ENTLA||IDA||a||b||xG||yG||xA||yA)
    uint32_t size = 194 + n_bytes;
    *concat_m = (uint8_t*)malloc(size); // 194 = 2 + 64 * 3
    // *((uint16_t *)(concat_m)) = n_bytes << 3; //将n_bytes * 8 比特数copy到前两个字节, todo: 顺序
    uint8_t *p = *concat_m;
    uint16_t n_bits = n_bytes << 3;
    *p++ = (uint8_t)(n_bits>>8);
    *p++ = (uint8_t)n_bits;
//    copy_reverse(concat_m, (uint8_t*)(&n_bits), 2);
    // p += 2;
    memcpy(p, id, n_bytes);
    p += n_bytes;
//    (void)ILib_memcpy(concat_m, &n_bits, 2);

//    uint32_t *p = (uint32_t*)(concat_m + (2 + n_bytes));
    copy_bn(p, SM2_A);
    p+=32;
    copy_bn(p, SM2_B);
    p+=32;
    copy_bn(p, SM2_G.x);
    p+=32;
    copy_bn(p, SM2_G.y);
    p+=32;
    int i;
    for(i=0; i<64; i++){
    	*p++ = *pub++;
    }

//    char str_concat[size*2+1];
//    bytes_to_hex_string(str_concat, concat_m, size);
    return size;
}

void copy_bytes(uint8_t *dist, uint8_t *src, uint32_t size)
{
	if(dist){
		while(size > 0){
			*dist++ = *src++;
			size--;
		}
	}
}


void print_bytes(uint8_t *m, size_t size)
{
    for (size_t i = 0; i < size; i++){
        printf("%02X", *m++);
    }
    putchar('\n');
}


void bytes_to_hex_string(uint8_t *hexStr, uint8_t* byte, uint32_t size) {
    // 将 uint8_t 数据转换为16进制字符串
	for(;size > 0; size--){
	    sprintf(hexStr, "%02X", *byte++);  // 使用大写16进制格式，确保输出两位
	    hexStr += 2;
	}
}
